<template>
  <div class="verification-code">
    <el-input v-model="userInput" placeholder="请输入验证码" @input="checkVerification"></el-input>
    <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" />
    <el-button type="primary" :disabled="!isVerified" @click="$emit('verified')">确认</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      captchaText: this.generateCaptcha(),
      isVerified: false
    };
  },
  computed: {
    captchaImage() {
      return `data:image/svg+xml;base64,${btoa(this.generateSVG())}`;
    }
  },
  methods: {
    generateCaptcha() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    generateSVG() {
      const svgWidth = 120;
      const svgHeight = 40;
      const fontSize = 20;
      const textX = 10;
      const textY = 30;

      let svgContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${svgWidth}" height="${svgHeight}">`;
      svgContent += `<rect width="100%" height="100%" fill="#f0f0f0" />`;
      svgContent += `<text x="${textX}" y="${textY}" font-family="Arial" font-size="${fontSize}" fill="#333">${this.captchaText}</text>`;
      svgContent += '</svg>';
      return svgContent;
    },
    refreshCaptcha() {
      this.captchaText = this.generateCaptcha();
      this.userInput = '';
      this.isVerified = false;
    },
    checkVerification() {
      this.isVerified = this.userInput.toUpperCase() === this.captchaText.toUpperCase();
    }
  }
};
</script>

<style scoped>
.verification-code {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-input {
  width: 150px;
}

img {
  cursor: pointer;
  width: 100px;
  height: 40px;
}
</style>
